package router

import (
	"gdshop-admin-go-api/app/service/AdminService"
	"gdshop-admin-go-api/library/response"
	"gdshop-admin-go-api/library/tools/token"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
	"github.com/gogf/gf/util/guid"
	"strings"
)

// MiddlewareErrorHandler 处理全局错误的
func MiddlewareErrorHandler(r *ghttp.Request) {
	r.SetCtxVar("trace_id", guid.S())
	r.Response.CORSDefault()
	if strings.Index(r.Request.URL.Path, "/upload") == -1 {
		// 不是上传的方法才打印
		logger.Ctx(r.GetCtx()).Async().Cat("router").Debug("路由：" + r.Request.URL.Path)
		logger.Ctx(r.GetCtx()).Async().Cat("router").Debug("Query：" + r.Request.URL.RawQuery)
		logger.Ctx(r.GetCtx()).Async().Cat("router").Debug("body：\n" + r.GetBodyString())
	}

	r.Middleware.Next()
	//fmt.Println(r)

	if err := r.GetError(); err != nil {
		// 记录到自定义错误日志文件
		g.Log("exception").Error(err)
		//返回固定的友好信息
		r.Response.ClearBuffer()
		response.JsonExit(r, 1, err.Error())
	}
}

// MiddlewareIsMemberLogin 会员登录 中间件
func MiddlewareIsMemberLogin(r *ghttp.Request) {
	if token.CheckToken(r) {
		r.Middleware.Next()
		return
	} else {
		r.Response.ClearBuffer()
		response.JsonExit(r, 10003, "请登录后继续操作")
		return
	}
}

// MiddlewareMemberPermissions 会员权限 中间件
func MiddlewareMemberPermissions(r *ghttp.Request) {
	if AdminService.CheckPermissions(r) {
		r.Middleware.Next()
		return
	} else {
		r.Response.ClearBuffer()
		response.JsonExit(r, 1, "没有操作权限")
		return
	}
}

// MiddlewareFrontApiCheck 前端API检测
func MiddlewareFrontApiCheck(r *ghttp.Request) {
	r.Middleware.Next()
	return
	/*if AdminService.CheckPermissions(r) {
		r.Middleware.Next()
		return
	} else {
		r.Response.ClearBuffer()
		response.JsonExit(r, 1, "没有操作权限")
		return
	}*/
}
